import SwiftUI

// RegisterButton
// 注册界面小窗口按钮

struct RegisterButton: View {
    @Environment(\.modelContext) private var modelContext
    
    @StateObject private var loginregisterRequester = LoginregisterRequester()
    
    @Environment(\.dismiss) private var dismiss
    
    @State private var isRegisterRequesting: Bool = false
    
    @Binding var phoneNumberInput: String
    @Binding var passwordInput: String
    @Binding var passwordRepeat: String
    
    @Binding var largeTitleText: String
    
    @Binding var registerStatus: Bool
    
    var body: some View {
        VStack() {
            Button {
                if passwordInput == passwordRepeat {
                    withAnimation {
                        isRegisterRequesting.toggle()
                    }
                    loginregisterRequester.request(phoneNumberInput, passwordInput)
                } else {
                    largeTitleText = "两次输入的密码不一致"
                }
            } label: {
                Spacer()
                if isRegisterRequesting {
                    ProgressView()
                        .progressViewStyle(CircularProgressViewStyle())
                        .tint(.white)
                        .padding(.vertical, 15)
                } else {
                    Text("注册")
                        .foregroundColor(.white)
                        .font(.title2)
                        .padding(.vertical, 12)
                }
                Spacer()
            }
            .disabled(isRegisterRequesting)
            .background(.accent)
            .cornerRadius(8)
        }
        .padding(.horizontal)
        .onChange(of: loginregisterRequester.requestStatus) { oldValue, newValue in
            if(oldValue == .requesting && newValue == .finish) {
                isRegisterRequesting.toggle()
                if(loginregisterRequester.publishedResult.status) {
                    dismiss()
                    registerStatus = true
                } else {
                    largeTitleText = loginregisterRequester.publishedResult.description
                }
            }
        }
    }
}

#Preview {
    RegisterButton(phoneNumberInput: .constant("18102676918"),
                   passwordInput: .constant("jby031216"),
                   passwordRepeat: .constant("jby031216"),
                   largeTitleText: .constant("欢迎"),
                   registerStatus: .constant(false))
}
